package com.example.entity.restTemplate;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.testng.annotations.Test;

/**
 * @Author yudong
 * @Date 2023/3/1 17:34
 * @description：
 */
public class MyRestTemplate{

    public <T> String template(String url, String contentType, String cookie, T params){
        RestTemplate client=new RestTemplate();
        client.setErrorHandler(new MyResponseErrorHandler()); //设置自定义请求失败异常处理

        HttpComponentsClientHttpRequestFactory requestFactory=new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);
        requestFactory.setReadTimeout(20000);
        client.setRequestFactory(requestFactory);

        // headers
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type",contentType);
        headers.add("Cookie",cookie); //如果非空
        headers.add("User-Agent","");

        HttpEntity<T> request = new HttpEntity<>(params, headers);

        try{
            ResponseEntity<String> response = client.postForEntity(url, request, String.class);
            return response.getBody();
        }catch(HttpClientErrorException e){
            return e.getResponseBodyAsString();
        }catch (Exception e){
            return e.toString();
        }

    }

    @Test // get 无参
    protected void get() {
        String url = "http://localhost:8081/people/selectByPeople";
        JSONObject params=new JSONObject();
        params.put("id",1);

        String template = new MyRestTemplate().template(url, MediaType.APPLICATION_JSON.toString(), null, params);
        System.out.println(template);
    }

}
